'use strict';
/**
 * sub class the base store
 */
var LoginConstants = require('../constants/login');
var LOGIN_USER = LoginConstants.LOGIN_USER;
var LOGOUT_USER = LoginConstants.LOGOUT_USER;
var jwt_decode = require('jwt-decode');
var EventEmitter = require('events').EventEmitter;
var AppDispatcher = require('../dispatchers/AppDispatcher');
var assign = require('object-assign');


var LoginStore = assign({} , EventEmitter.prototype , {
	_user: null,
	_jwt: null,

	subscribe: function(actionSubscribe) {
		this._dispatchToken = AppDispatcher.register(actionSubscribe());
	},

	dispatchToken: function() {
		return this._dispatchToken;
	},

	emitChange: function() {
		this.emit('CHANGE');
	},

	addChangeListener: function(cb) {
		this.on('CHANGE' , cb);
	},

	removeChangeListener: function(cb) {
		this.removeListener('CHANGE' , cb);
	},

	_registerToActions: function(action)
	{
		switch (action.actionType) {
			case LOGIN_USER:
				this._jwt = action._jwt;
				this._user = jwt_decode(this._jwt);
				this.emitChange();
				break;
			case LOGOUT_USER:
				this._user = null;
				this.emitChange();
				break;
			default:
				break;
		}
	},

	user: function()
	{
		return this._user;
	},

	jwt: function()
	{
		return this._jwt;
	},

	isLoggedIn: function()
	{
		return !!this._user;
	}
});

module.exports = LoginStore;
